package com.xiaxinyu.redis.client.service;

import com.xiaxinyu.redis.client.api.RedisAPI;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

/**
 * @author XIAXINYU3
 * @date 2021/6/8
 */
@Slf4j
@Component
public class RedisCounter {
    @Autowired
    @Qualifier("redisThreadPool")
    AsyncTaskExecutor asyncTaskExecutor;

    @Autowired
    RedisTemplate redisTemplate;

    private static final String KEY = "counter";

    public void test() {
        redisTemplate.delete(KEY);

        for (int i = 0; i < 1000; i++) {
            asyncTaskExecutor.execute(() -> {
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                String counter = get();
                set(Integer.valueOf(counter) + 1);
            });
        }

        System.out.println("运行结束......");
    }

    public String get() {
        if (!redisTemplate.hasKey(KEY)) {
            log.info("创建key......");
            redisTemplate.opsForValue().set(KEY, 1);
        }
        return redisTemplate.opsForValue().get(KEY).toString();
    }

    public void set(int value) {
        log.info("设置值：value={}", value);
        redisTemplate.opsForValue().set(KEY, value);
    }
}
